﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace AndreySmirnov.BLToolkitUtils.VSPackage.Model.ViewModel
{
	public class EncryptedConnInfoViewModel : ViewModelBase
	{
		private const string USER_NAME_KEY = "User Id";
		private const string PASSWORD_KEY = "Password";

		private readonly BLTConnectionInfo m_connVM;

		public EncryptedConnInfoViewModel(BLTConnectionInfo connVM)
		{
			m_connVM = connVM;
		}

		private string ParseConnectionData(string valName)
		{
			//User Id=AsmiTechWebSite;Password=AsmiTechWebSitePass
			//TODO decrypt data
			var values = m_connVM.CredentialsData.Split(new []{";"}, StringSplitOptions.RemoveEmptyEntries);
			var dict = values.Select(s => s.Split(new[] {"="}, StringSplitOptions.RemoveEmptyEntries))
				.Where(parts => parts.Length == 2)
				.ToDictionary(parts => parts[0].Trim(), parts => parts[1].Trim());
			if (!dict.ContainsKey(valName))
				return string.Empty;
			return dict[valName];
		}

		private void UpdateConnectionData(string valName, string value)
		{
			var res = string.Format("{0}={1};{2}={3}", 
				USER_NAME_KEY, (valName == USER_NAME_KEY) ? value : UserName,
				PASSWORD_KEY, (valName == PASSWORD_KEY) ? value : Password);
			//TODO encrypt data
			m_connVM.CredentialsData = res;
		}

		public string UserName
		{
			get
			{
				return ParseConnectionData(USER_NAME_KEY);
			}
			set
			{
				UpdateConnectionData(USER_NAME_KEY, value);
				NotifyPropertyChange("UserName");
			}
		}

		public string Password
		{
			get
			{
				return ParseConnectionData(PASSWORD_KEY);
			}
			set
			{
				UpdateConnectionData(PASSWORD_KEY, value);
				NotifyPropertyChange("Password");
			}
		}
	}
}
